package com.bestattempt.utility.bind.initializers.defaultImpl;

import static com.bestattempt.utility.reflection.ReflectionUtil.getFieldValue;
import static com.bestattempt.utility.reflection.ReflectionUtil.newInstance;
import static com.bestattempt.utility.reflection.ReflectionUtil.setFieldValue;
import com.bestattempt.utility.bind.initializers.AbstractInitializer;

import java.lang.reflect.Field;

/**
 * Initializes an object whose field is not a collection.
 *
 * @author Ganeshji Marwaha
 * @since Oct 14, 2006
 */
public class ObjectInitializer extends AbstractInitializer {

    public Object initialize(Object obj, Field field) {
        Object o = getFieldValue(obj, field);
        if(o == null) {
            o = newInstance(field.getType());
            setFieldValue(obj, field, o);
        }
        return o;
    }

    public Object initialize(Object toInitialize, Field toInstantiate, String index) {
        throw new UnsupportedOperationException("Indexed properties cannot be initialized by me");
    }    
}
